package com.fanben100.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.ParseException;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

import com.fanben100.biz.InnerPropertyStrategy;
import com.fanben100.biz.LogonState;
import com.fanben100.biz.OuterPropertyStrategy;
import com.fanben100.biz.RegistContext;
import com.fanben100.biz.SysConfigContext;
import com.fanben100.biz.SysConfigStrategy;
import com.fanben100.biz.ValidLoginModel;
import com.fanben100.constant.SystemConstant;
import com.fanben100.domain.LoginModel;
import com.fanben100.domain.Seller;
import com.fanben100.domain.SysConfig;
import com.fanben100.exception.LoadConfigException;
import com.fanben100.util.CryptoTools;
import com.fanben100.util.DialogUtil;
import com.fanben100.util.IdentityUtil;
import com.fanben100.util.SerializeUtil;

public class SellerRegistDialog extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// private JLabel sellerIdLabel = new JLabel("商家编号:", JLabel.LEFT);
	// private JLabel sellerIdContentLabel = new JLabel("", Label.LEFT);

	private JLabel sellerNameLable = new JLabel("商家账号:", JLabel.LEFT);
	private JTextField sellerNameField = new JTextField(20);

	private JLabel sellerPasswordLabel = new JLabel("商家密码:", JLabel.LEFT);
	private JPasswordField sellerPasswordField = new JPasswordField(20);

	private JLabel sellerIdentifyLabel = new JLabel("身份证号:", JLabel.LEFT);
	private JTextField sellerIdentifyField = new JTextField(20);

	private JButton registButton = new JButton("注册");

	public SellerRegistDialog(JFrame frame, String title, boolean modal) {
		super(frame, title, modal);
		this.setSize(new Dimension(180, 100));
		this.setLocationRelativeTo(frame);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				dispose();
			}
		});
		try {
			jbInit();
			pack();
			// getContentPane().setSize(500, 400);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	// public SellerRegistDialog() {
	// this(null, "注册商家", true);
	// }

	private void jbInit() {

		// Integer sellerId = SysConfig.sellerId;
		// String sellerName = SysConfig.sellerName;

		Object registModel = SerializeUtil
				.deserialize(SystemConstant.KEY_STORE_NAME);
		if (registModel == null || !(registModel instanceof Seller)) {
			// if (sellerId == null) {
			// SysConfig.sellerId = Integer.valueOf(PropertyUtils.readValue(
			// SystemConstant.UI_CONFIG_PATH,
			// SystemConstant.SELLER_ID_KEY, null));
			// }
			// if (sellerName == null) {
			// SysConfig.sellerName = PropertyUtils.readValue(
			// SystemConstant.UI_CONFIG_PATH,
			// SystemConstant.SELLER_NAME_KEY, null);
			// }
			if (SysConfig.sellerId == null) {
				SysConfigContext context = new SysConfigContext();
				SysConfigStrategy strategy = new InnerPropertyStrategy();
				context.setConfigStrategy(strategy);
				try {
					context.loadSysConfig();
				} catch (LoadConfigException lce) {
					lce.printStackTrace();
				}
				if (SysConfig.sellerId == null) {
					strategy = new OuterPropertyStrategy();
					context.setConfigStrategy(strategy);
					try {
						context.loadSysConfig();
					} catch (LoadConfigException e) {
						e.printStackTrace();
					}
				}
			}
		} else {
			Seller registSeller = (Seller) registModel;
			SysConfig.sellerId = registSeller.getSellerId();
			SysConfig.sellerName = registSeller.getSellerName();
			// SysConfig.sellerLoginModel =
		}
		this.setResizable(false);
		JPanel sellerRegistPanel = new JPanel(false);
		sellerRegistPanel.setLayout(new BoxLayout(sellerRegistPanel,
				BoxLayout.X_AXIS));

		// sellerIdLabel.setVisible(false);
		// sellerIdField = new JTextField();
		// sellerIdField.setEditable(false);
		// sellerIdField.setVisible(false);

		// sellerIdField.setSize(new Dimension(50, 10));
		// sellerIdField.setText(SysConfig.sellerId != null ? SysConfig.sellerId
		// .toString() : "");

		// sellerIdContentLabel
		// .setText(SysConfig.sellerId != null ? SysConfig.sellerId
		// .toString() : "");

		// sellerNameField.setEditable(false);
		sellerNameField.setAlignmentX(CENTER_ALIGNMENT);
		sellerNameField.setText(SysConfig.sellerName);

		Object source = SerializeUtil
				.deserialize(SystemConstant.KEY_STORE_NAME);

		if (source != null && source instanceof LoginModel) {
			LoginModel loginModel = (LoginModel) source;
			String encodePass = loginModel.getLoginPassword();
			String encodeIdentity = loginModel.getIdentify();
			String sourcePass = null;
			String sourceIdentity = null;
			try {
				sourcePass = CryptoTools.getInstance().decode(encodePass);
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				sourceIdentity = CryptoTools.getInstance().decode(encodeIdentity);
			} catch (Exception e) {
				e.printStackTrace();
			}
			loginModel.setLoginPassword(sourcePass);
			loginModel.setIdentify(sourceIdentity);
			// sellerIdField.setText(seller.getLoginId().toString());
			sellerPasswordField.setText(loginModel.getLoginPassword());
		}

		registButton.setSize(new Dimension(20, 10));
		registButton.addActionListener(new SellerRegistAction());
		registButton.registerKeyboardAction(new SellerRegistAction(),
				KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
				JComponent.WHEN_IN_FOCUSED_WINDOW);
		registButton.setAlignmentX((sellerRegistPanel.getWidth() - registButton
				.getWidth() / 2));

		sellerPasswordField.setEchoChar('*');

		JPanel labelPanel = new JPanel(false);
		labelPanel.setLayout(new GridLayout(0, 1));
		// labelPanel.add(sellerIdLabel);
		labelPanel.add(sellerNameLable);
		labelPanel.add(sellerPasswordLabel);
		labelPanel.add(sellerIdentifyLabel);

		JPanel fieldPanel = new JPanel(false);
		fieldPanel.setLayout(new GridLayout(0, 1));
		// fieldPanel.add(sellerIdContentLabel);
		fieldPanel.add(sellerNameField);
		fieldPanel.add(sellerPasswordField);
		fieldPanel.add(sellerIdentifyField);

		getContentPane().setLayout(new BorderLayout());

		sellerRegistPanel.add(labelPanel);
		sellerRegistPanel.add(fieldPanel);
		this.getContentPane().add(sellerRegistPanel, BorderLayout.CENTER);
		this.getContentPane().add(registButton, BorderLayout.PAGE_END);
		getContentPane().setSize(new Dimension(500, 400));
	}

	/**
	 * 商家注册Action
	 * 
	 * @author Administrator
	 * 
	 */
	private class SellerRegistAction implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			// if (!NumberUtil.isNumeric1(sellerIdContentLabel.getText())) {
			// // sellerIdContentLabel.setText("商家编号必须为数字。");
			// return;
			// }
			char[] password = sellerPasswordField.getPassword();
			if (password == null || password.length < 3) {
				JOptionPane.showMessageDialog(SellerRegistDialog.this,
						"密码未输入或输入格式不正确，密码必须大于三位");
				return;
			}
			String identityNo = sellerIdentifyField.getText();
			String validMsg = null;
			try {
				validMsg = IdentityUtil.IDCardValidate(identityNo);
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
			if (!"".equals(validMsg)) {
				JOptionPane
						.showMessageDialog(SellerRegistDialog.this, validMsg+"\n"+"身份证格式不正确，请进入网站系统进行更正");
				return;
			}
			LoginModel loginModel = new Seller();
			// loginModel.setLoginId(NumberUtil.tryParseInt(sellerIdContentLabel
			// .getText()));
			loginModel.setLoginId(SysConfig.sellerId);
			StringBuffer passwordBuffer = new StringBuffer();
			for (char pc : sellerPasswordField.getPassword()) {
				passwordBuffer.append(pc);
			}
			loginModel.setLoginId(sellerNameField.getText());
			loginModel.setLoginPassword(passwordBuffer.toString());
			loginModel.setIdentify(sellerIdentifyField.getText());
			ValidLoginModel res = RegistContext.getInstance()
					.regist(loginModel);
			if (res.isValid()) {
				JOptionPane.showMessageDialog(SellerRegistDialog.this, "注册成功");
				SysConfig.sellerLoginModel = res;
				SellerRegistDialog.this.dispose();
				if (RegistContext.getInstance().getSysState() == null
						|| !(RegistContext.getInstance().getSysState() instanceof LogonState)) {
					UserLoginDialog userLoginDialog = new UserLoginDialog(
							DialogUtil.getModalFrame(SellerRegistDialog.this),
							true);
					userLoginDialog.setVisible(true);
				}
				// DialogUtil.getModalFrame(SellerRegistDialog.this)
				// .getContentPane().setVisible(true);

			} else {
				JOptionPane.showMessageDialog(SellerRegistDialog.this,
						res.getValidMessage(), "注册失败",
						JOptionPane.ERROR_MESSAGE);
			}
		}

	}

	// /**
	// * 重写该方法实现主窗体卸载
	// */
	// @Override
	// protected void processWindowEvent(WindowEvent e) {
	// SystemState currentState = RegistContext.getInstance().getSysState();
	// boolean currentLogon = currentState instanceof LogonState;
	// // 如果当前登录状态为已登录，不强制退出系统
	// if (e.getID() == WindowEvent.WINDOW_CLOSING && !currentLogon) {
	// Container container = this.getParent(), root = container;
	// while (container != null) {
	// root = container;
	// container = container.getParent();
	// if (container instanceof TerminalFrame) {
	// break;
	// }
	// }
	// if (root != null && root instanceof TerminalFrame) {
	// TerminalFrame frame = (TerminalFrame) root;
	// frame.dispose();
	// System.exit(0);
	// }
	// }
	// super.processWindowEvent(e);
	// }
}
